package scau.jump.rfid.driver.console;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import scau.jump.rfid.driver.Address;
import scau.jump.rfid.driver.Writer;

public class ConsoleWriter implements Writer {

	public void write(Address address, String data) throws IOException {
		writeTo((LineAddress) address, data);
	}

	private void writeTo(LineAddress address, String data) throws IOException {
		String msg = "";
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(new File(address.getFile())));
			int lineNum = 1;
			String line = null;
			
			while((line = reader.readLine()) != null) {
				msg += line + "\n";
				if(lineNum == address.getLine()) {
					msg += data + "\n";
				}
				lineNum ++;
			}
			
		} catch (FileNotFoundException e) {
			throw new IOException(e);
		} finally {
			if(reader != null) {
				reader.close();
			}
		}
		
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(new File(address.getFile())));
			writer.write(msg);
			writer.flush();
		} finally {
			if(writer != null)
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		
	}

}
